/*
 * @Description: 请求钩子函数
 * @Author: 林文琛
 * @Date: 2022-04-13 15:06:45
 * @LastEditTime: 2022-11-09 10:32:19
 * @LastEditors: ljt
 */

import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import axios from 'axios';
import type { RequestParams, ResponseRes } from './RequestType'
import { ElMessageBox, ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import {
    removeToken, removeUserUnitName, removeRolesMes, removeUserInfo
} from '@/utils/auth'
const router = useRouter();
const route = useRoute();

/**
 * @name: initInterceptors
 * @Date: 2022-04-13 16:49:27
 * @description: 初始化拦截器
 * @param {any} axiosInstance
 * @return {*} 请求结果
 */
import store from '@/store/index'
const initInterceptors = (axiosInstance: any): any => {
    // 请求拦截器
    axiosInstance.interceptors.request.use(
        // 请求已发出
        (reqCfg: AxiosRequestConfig) => {
            // console.log('请求拦截器', reqCfg);
            // 每次请求前，如果存在token则在请求头中携带token
            // 测试token
            // let testToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MTA2OTEwMzcsInVzZXJuYW1lIjoiQWlQbGF0Zm9ybSJ9.lB8m6RhaXU7vCqujjcF7XMnVP2GXCq_fLkD3J1_6oto'

            const token = localStorage.getItem('token')
            if (token) {
                reqCfg.headers!['X-Access-Token'] = `${token}` // 携带token请求头
            }
            // 设置post请求头
            if (reqCfg.method == 'post' || reqCfg.method == 'put' || reqCfg.method == 'delete') {
                reqCfg.headers!['Content-Type'] = 'application/json'
            }
            // console.log('请求配置', reqCfg)
            return reqCfg
        },
        // 请求未发出
        (error: any) => {
            console.log(' 请求未发出', error)
            if (error == "Error: Request failed with status code 401") {

                ElMessage({
                    message: "登录已过期，请重新登录!",
                    type: "error",
                    duration: 2000,
                });
                removeToken()
                removeRolesMes()
                removeUserInfo()
                removeUserUnitName()
                // router && router.go(0)
                location.reload()//刷新
                router && router.push('/login');
            } else if (error == "Error: timeout of 10000ms exceeded") {
                ElMessage({
                    message: "请求超时，请稍等再重试!",
                    type: "error",
                    duration: 2000,
                });
            } else if (error == "Error: Request failed with status code 500") {
                ElMessage({
                    message: "连接服务端失败，请重启服务!",
                    type: "error",
                    duration: 3000,
                });
            } else {
                ElMessage({
                    message: error.message,
                    type: "error",
                    duration: 5 * 1000,
                });
            }
            return Promise.reject(error);
        }
    )
    /**
     * response.data.code
     * 煜邦：100 调用成功 200服务不可用 401缺少必填参数 402非法参数
     */
    // 响应拦截器
    axiosInstance.interceptors.response.use(
        // 响应成功
        (response: AxiosResponse): any => {
            // console.log('响应拦截器', response);
            let result: ResponseRes
            if (response.status === 200) { // 待完善！！！！
                if (response.config.url!.match(/^\/local|^\/producer/)) {
                    switch (response.data.code) {
                        case '100':
                            result = {
                                success: true,
                                status: 200,
                                data: { ...response.data, success: true },
                                error: null
                            }
                            break
                        default:
                            result = {
                                success: false,
                                status: 200,
                                data: { ...response.data, success: false },
                                error: response.data.msg
                            }
                        // console.error(response.data.msg)
                    }
                } else {
                    switch (response.data.code) {
                        case 0:
                            result = {
                                success: true,
                                status: 200,
                                data: { ...response.data, success: true }, // 这一步是为了统一煜邦和智瞰里面都有success字段
                                error: null
                            }
                            break
                        default:
                            result = {
                                success: false,
                                status: 200,
                                data: { ...response.data, success: false },
                                error: response.data.msg
                            }
                        // console.error(response.data.msg)
                    }
                }
                return result
                // if (response.data.code === 200 || response.data.code === 1) {
                //     let result: ResponseRes = {
                //         success: true,
                //         status: 200,
                //         data: response.data,
                //         error: null
                //     }
                //     return result
                // } else if (response.data.code === -1) {
                //     return errorHandle(response)
                // } else {
                //     let result: ResponseRes = {
                //         success: false,
                //         status: 200,
                //         data: response.data,
                //         error: response.data.msg
                //     }
                //     return result
                // }
            } else if (response.status === 401) {
                ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // store.dispatch('LogOut').then(() => {
                    //   location.href = '/index';
                    // })
                    removeToken()
                    removeRolesMes()
                    removeUserUnitName()
                    removeUserInfo()
                    // router && router.go(0)
                    location.reload()//刷新
                    router && router.push('/login');
                }).catch(() => {
                });
                return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
            } else {
                return errorHandle(response)
            }
        },
        // 响应失败
        (error: any) => {
            console.log('响应失败', error);


            // debugger
            const { response } = error
            if (response) {
                if (response.status == 401) {
                    if (document.getElementsByClassName('el-message').length === 0) {
                        ElMessage({
                            message: response?.data?.message || "请重新登录!",
                            type: "error",
                        });
                    }
                    removeToken()
                    removeRolesMes()
                    removeUserInfo()
                    removeUserUnitName()
                    // router && router.go(0)
                    location.reload()//刷新
                    router && router.push('/login');
                } else if (response.data?.code !== 200) {
                    response?.data?.message && ElMessage({
                        message: response?.data?.message,
                        type: "error",
                    });

                }
                // 状态码不在2xx的范围
                return errorHandle(response)
            } else {
                // 网络连接异常
                let result: ResponseRes = {
                    success: false,
                    status: null,
                    data: null,
                    error: '网络连接异常！'
                }
                // console.error('网络连接异常！')
                return result
            }
        }
    )
}

/**
 * @name: errorHandle
 * @Date: 2022-04-13 17:21:58
 * @description: http握手失败时的处理
 * @param {any} res 响应的内容
 * @return {ResponseRes} 请求结果
 */
const errorHandle = (res: any): ResponseRes => {
    let result: ResponseRes
    // 状态码判断
    switch (res.status) {
        case 401:
            result = {
                success: false,
                status: 401,
                data: null,
                error: '没有访问权限！'
            }
            console.error('没有访问权限！')
            return result
        case 403:
            result = {
                success: false,
                status: 403,
                data: null,
                error: '服务器拒绝请求！'
            }
            console.error('服务器拒绝请求！')
            return result
        case 404:
            result = {
                success: false,
                status: 404,
                data: null,
                error: '请求的资源不存在！'
            }
            console.error('请求的资源不存在！')
            return result
        default:
            const msg = res.data.msg || res.statusText || '请求错误！'
            result = {
                success: false,
                status: res.status,
                data: null,
                error: msg
            }
            // console.error(msg)
            return result
    }
}

/**
 * @name: useAxios
 * @Date: 2022-04-19 14:11:15
 * @description: 请求钩子函数，用于发起请求
 * @param {RequestParams} params 请求参数
 * @return {Promise<ResponseRes>} 响应结果
 */
const useAxios = async (params: RequestParams): Promise<ResponseRes> => {
    let axiosInstance: AxiosInstance = axios.create({
        baseURL: params.base,
        timeout: 30 * 1000
    })
    initInterceptors(axiosInstance);

    let requestConfig: AxiosRequestConfig = {
        url: params.api,
        headers: params.headers,
        method: params.method,
        params: params.params,
        data: params.data
    };
    // params.method === "GET" ? requestConfig.params = params.data : requestConfig.data = params.data;
    return axiosInstance(requestConfig) as unknown as ResponseRes
}

export default useAxios;
